<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use lib\Curl;
use lib\WxpayTmd;
use lib\UserCrypt;
class Orders extends Base{
    private $appid='wx73b2fe7a7e0dab2c';
    private $mch_id='1375626302';
    private $apikey='eih0cfnmokla4nxwo4w0ioqvmtracc1c';
	// 单产品下单
	public function orderIn()
	{
		if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.openid"))){
            $openid=input("param.openid");
        }else{
            return json(['code' => 505, 'msg' => 'openid呢？']);
        }
        if(!empty(input("param.p_id"))){
            $data['p_id']=input("param.p_id");
        }else{
            return json(['code' => 502, 'msg' => '产品id']);
        }
        if(!empty(input("param.buy_num"))){
            $data['buy_num']=input("param.buy_num");
        }else{
            return json(['code' => 503, 'msg' => '购买数量']);
        }
        if(!empty(input("param.price"))){
            $data['price']=input("param.price");
        }else{
            return json(['code' => 504, 'msg' => '单价']);
        }
        $data['deduct_moneys']=input("param.deduct_moneys");
        if(!empty(input("param.pay_fees"))){
            $data['pay_fees']=input("param.pay_fees");
        }else{
            return json(['code' => 506, 'msg' => '支付金额']);
        }
        if(!empty(input("param.spec_combination_id"))){
            $data['spec_combination_id']=input("param.spec_combination_id");
        }else{
            return json(['code' => 507, 'msg' => '参数spec_combination_id']);
        }
        if(!empty(input("param.name"))){
            $data['name']=input("param.name");
        }else{
            return json(['code' => 508, 'msg' => '收货人']);
        }
        if(!empty(input("param.phone"))){
            $data['phone']=input("param.phone");
        }else{
            return json(['code' => 509, 'msg' => '收货电话']);
        }
        if(!empty(input("param.address"))){
            $data['address']=input("param.address");
        }else{
            return json(['code' => 510, 'msg' => '收货地址']);
        }
        if(!empty(input("param.address_id"))){
            $data['address_id']=input("param.address_id");
        }else{
            return json(['code' => 513, 'msg' => '默认收货地址id']);
        }
        if(!empty(input("param.message"))){
            $data['message']=input("param.message");
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $body=Db::name('product')->where('id',$data['p_id'])->value('title');
        $data['user_id']=$uid;
        $data['pay_style']=2;
        $data['combination']=Db::name('spec_combination')->where('id',$data['spec_combination_id'])->value('combination');
        $data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
        $data['state']=1;
        $data['is_cart']=1;
        $data['sub']=1;
        $data['order_type']=1;
        $data['time']=time();
        $data['uptime']=time();

        $commission_scale=Db::name('system_set')->where('id',1)->value('commission_scale');//购买n元上级获佣金比例
        $commission=bcmul($data['pay_fees'],bcdiv($commission_scale,100,4),2);

        Db::startTrans();
        try {
            $orderId=Db::name('orders')->insertGetId($data);
            $datasub['user_id']=$uid;
            $datasub['orders_id']=$orderId;
            $datasub['title']=$body;
            $datasub['ordernosub']=$data['orderno'].'1';
            $datasub['cart_id']=0;
            $datasub['p_id']=$data['p_id'];
            $datasub['buy_num']=$data['buy_num'];
            $datasub['deduct_money']=$data['deduct_moneys'];
            $datasub['pay_fee']=$data['pay_fees'];
            $datasub['price']=$data['price'];
            $datasub['spec_combination_id']=$data['spec_combination_id'];
            $datasub['combination']=$data['combination'];
            $datasub['order_type']=1;
            $datasub['state']=1;
            $datasub['time']=time();
            $datasub['uptime']=time();
            $ordersubId=Db::name('ordersub')->insertGetId($datasub);
            Db::name('spec_combination')->where('id',$data['spec_combination_id'])->setDec('num',$data['buy_num']);//减库存
            
            //佣金抵扣
            if ($data['deduct_moneys']>0) {
                Db::name('users')->where('id', $uid)->setDec('money',$data['deduct_moneys']);
                $datascore2['user_id']=$uid;
                $datascore2['orders_id']=$ordersubId;
                $datascore2['money']=$data['deduct_moneys'];
                $datascore2['type']=2;
                $datascore2['time']=time();
                $datascore2['uptime']=time();
                Db::name('money_bill')->insertGetId($datascore2);
            }
            // 提交事务
            Db::commit();
            $weixinpay = new WxpayTmd($this->appid,$openid,$this->mch_id,$this->apikey,$data['orderno'],$body,floatval($data['pay_fees'] * 100),$this->request->domain());
            $return=$weixinpay->pay();
            return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '事物回滚失败！']);
        }
	}
    public function notify()
    {
        $input = file_get_contents('php://input');
        $pay_result = simplexml_load_string($input, 'SimpleXMLElement',LIBXML_NOCDATA);
        if($pay_result->result_code=='SUCCESS'&&$pay_result->return_code=='SUCCESS'){
            $orders_id=Db::name('orders')->where('orderno',$pay_result->out_trade_no)->find();
            if($orders_id){
                if($orders_id['state']==1){
                    Db::name('orders')->where('orderno',$pay_result->out_trade_no)->update(['state'=>2,'uptime'=>time(),'fktime'=>time()]);
                    Db::name('ordersub')->where('orders_id',$orders_id['id'])->update(['state'=>2,'uptime'=>time(),'fktime'=>time()]);
                    //挣佣金
                    $invite_id=Db::name('users')->where('id', $orders_id['user_id'])->value('invite_id');
                    $commission_scale=Db::name('system_set')->where('id',1)->value('commission_scale');//购买n元上级获佣金比例
                    $commission=bcmul($orders_id['pay_fees'],bcdiv($commission_scale,100,4),2);
                    if ($invite_id>0&&$commission>0) {
                        Db::name('users')->where('id',$invite_id)->setInc('money',$commission);
                        $datascore1['user_id']=$invite_id;
                        $datascore1['orders_id']=Db::name('ordersub')->where('orders_id',$orders_id['id'])->value('id');
                        $datascore1['money']=$commission;
                        $datascore1['type']=1;
                        $datascore1['time']=time();
                        $datascore1['uptime']=time();
                        Db::name('money_bill')->insertGetId($datascore1);
                    }
                }
            }else{
                $orders_id=Db::name('ordersub')->where('ordernosub',$pay_result->out_trade_no)->find();
                if($orders_id['state']==1){
                    Db::name('ordersub')->where('ordernosub',$pay_result->out_trade_no)->update(['state'=>2,'uptime'=>time(),'fktime'=>time()]);
                    //挣佣金
                    $invite_id=Db::name('users')->where('id', $orders_id['user_id'])->value('invite_id');
                    $commission_scale=Db::name('system_set')->where('id',1)->value('commission_scale');//购买n元上级获佣金比例
                    $commission=bcmul($orders_id['pay_fee'],bcdiv($commission_scale,100,4),2);
                    if ($invite_id>0&&$commission>0) {
                        Db::name('users')->where('id',$invite_id)->setInc('money',$commission);
                        $datascore1['user_id']=$invite_id;
                        $datascore1['orders_id']=$orders_id['id'];
                        $datascore1['money']=$commission;
                        $datascore1['type']=1;
                        $datascore1['time']=time();
                        $datascore1['uptime']=time();
                        Db::name('money_bill')->insertGetId($datascore1);
                    }
                }
            }
        }
        
    }
	// 我的订单
	public function myOrders()
	{
		if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.page"))){
            $page=input("param.page");
        }else{
            return json(['code' => 502, 'msg' => '当前分页数']);
        }
        $keyword=input('param.keyword');
        if(input("param.state")==1||input("param.state")==2||input("param.state")==3||input("param.state")==4||input("param.state")==5||input("param.state")==6){
	        $map = [
            	['state', '=', input("param.state")]
	        ];
        }else{
	        $map = [
            	['state', '<', 7]
	        ];
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $res=Db::name('ordersub')->where($map)->where('user_id',$uid)->where('title|ordernosub','like',"%{$keyword}%")->order('id desc')->limit(10*($page-1),10)->select();
        if ($res) {
        	foreach ($res as $k => $v) {
        		$res[$k]['time']=date('Y-m-d H:i:s',$res[$k]['time']);
                if($res[$k]['order_type']==1){
                    $res[$k]['img']=Db::name('product')->where('id',$res[$k]['p_id'])->value('img');
                }elseif($res[$k]['order_type']==2){
                    $res[$k]['img']=Db::name('scenic_spot')->where('id',$res[$k]['p_id'])->value('img');
                }
        	}
            return json(['code' => 200, 'msg' => '成功！','data'=>$res]);
		}else{
            return json(['code' => 500, 'msg' => '查无数据！']);
		}
	}
	//订单详情
    public function orderDetail(){
        if(!empty(input("param.id"))){
            $id=input("param.id");
        }else{
            return json(['code' => 501, 'msg' => '详情id呢？']);
        }
        $res=Db::name('ordersub')->alias('a')->join('orders b', 'a.orders_id = b.id','LEFT')->where('a.id',$id)->field('a.*,b.name,b.phone,b.address')->find();
        if($res){
            if($res['order_type']==1){
                $res['img']=Db::name('product')->where('id',$res['p_id'])->value('img');
            }elseif($res['order_type']==2){
                $res['img']=Db::name('scenic_spot')->where('id',$res['p_id'])->value('img');
            }
        	$res['time']=date('Y-m-d H:i:s',$res['time']);
            if($res['fktime']>0){
                $res['fktime']=date('Y-m-d H:i:s',$res['fktime']);
            }else{
                $res['fktime']='';
            }
            if($res['fhtime']>0){
                $res['fhtime']=date('Y-m-d H:i:s',$res['fhtime']);
            }else{
                $res['fhtime']='';
            }
            return json(['code' => 200, 'msg' => '查询成功' ,'data' =>$res]);
        }else{
            return json(['code' => 500, 'msg' => '查无结果']);
        }
    }
    // 门票下单
    public function spotOrderin()
    {
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.openid"))){
            $openid=input("param.openid");
        }else{
            return json(['code' => 505, 'msg' => 'openid呢？']);
        }
        if(!empty(input("param.p_id"))){
            $data['p_id']=input("param.p_id");
        }else{
            return json(['code' => 502, 'msg' => '产品id']);
        }
        if(!empty(input("param.buy_num"))){
            $data['buy_num']=input("param.buy_num");
        }else{
            return json(['code' => 503, 'msg' => '购买数量']);
        }
        if(!empty(input("param.price"))){
            $data['price']=input("param.price");
        }else{
            return json(['code' => 504, 'msg' => '单价']);
        }
        $data['deduct_moneys']=input("param.deduct_moneys");
        if(!empty(input("param.pay_fees"))){
            $data['pay_fees']=input("param.pay_fees");
        }else{
            return json(['code' => 506, 'msg' => '支付金额']);
        }
        if(!empty(input("param.name"))){
            $data['name']=input("param.name");
        }else{
            return json(['code' => 508, 'msg' => '收货人']);
        }
        if(!empty(input("param.phone"))){
            $data['phone']=input("param.phone");
        }else{
            return json(['code' => 509, 'msg' => '收货电话']);
        }
        if(!empty(input("param.address"))){
            $data['address']=input("param.address");
        }else{
            return json(['code' => 510, 'msg' => '收货地址']);
        }
        if(!empty(input("param.address_id"))){
            $data['address_id']=input("param.address_id");
        }else{
            return json(['code' => 513, 'msg' => '默认收货地址id']);
        }
        if(!empty(input("param.message"))){
            $data['message']=input("param.message");
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $body=Db::name('scenic_spot')->where('id',$data['p_id'])->value('title');
        $data['user_id']=$uid;
        $data['pay_style']=2;
        $data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
        if ($data['price']==0&&$data['pay_fees']==0) {
            $data['state']=2;
        }else{
            $data['state']=1;
        }
        $data['is_cart']=1;
        $data['sub']=1;
        $data['order_type']=2;
        $data['time']=time();
        $data['uptime']=time();

        $commission_scale=Db::name('system_set')->where('id',1)->value('commission_scale');//购买n元上级获佣金比例
        $commission=bcmul($data['pay_fees'],bcdiv($commission_scale,100,4),2);

        Db::startTrans();
        try {
            $orderId=Db::name('orders')->insertGetId($data);
            $datasub['user_id']=$uid;
            $datasub['orders_id']=$orderId;
            $datasub['title']=$body;
            $datasub['ordernosub']=$data['orderno'].'1';
            $datasub['cart_id']=0;
            $datasub['p_id']=$data['p_id'];
            $datasub['buy_num']=$data['buy_num'];
            $datasub['deduct_money']=$data['deduct_moneys'];
            $datasub['pay_fee']=$data['pay_fees'];
            $datasub['price']=$data['price'];
            $datasub['order_type']=2;
            $datasub['state']=$data['state'];
            $datasub['time']=time();
            $datasub['uptime']=time();
            $ordersubId=Db::name('ordersub')->insertGetId($datasub);
            // //挣佣金
            // $invite_id=Db::name('users')->where('id', $uid)->value('invite_id');
            // if ($invite_id>0&&$commission>0) {
            //     Db::name('users')->where('id',$invite_id)->setInc('money',$commission);
            //     $datascore1['user_id']=$invite_id;
            //     $datascore1['orders_id']=$orderId;
            //     $datascore1['money']=$commission;
            //     $datascore1['type']=1;
            //     $datascore1['time']=time();
            //     Db::name('money_bill')->insertGetId($datascore1);
            // }
            //佣金抵扣
            if ($data['deduct_moneys']>0) {
                Db::name('users')->where('id', $uid)->setDec('money',$data['deduct_moneys']);
                $datascore2['user_id']=$uid;
                $datascore2['orders_id']=$ordersubId;
                $datascore2['money']=$data['deduct_moneys'];
                $datascore2['type']=2;
                $datascore2['time']=time();
                $datascore2['uptime']=time();
                Db::name('money_bill')->insertGetId($datascore2);
            }
            // 提交事务
            Db::commit();
            $weixinpay = new WxpayTmd($this->appid,$openid,$this->mch_id,$this->apikey,$data['orderno'],$body,floatval($data['pay_fees'] * 100),$this->request->domain());
            $return=$weixinpay->pay();
            return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '事物回滚失败！']);
        }
    }
    // 购物车下单
    public function corderIn()
    {
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.openid"))){
            $openid=input("param.openid");
        }else{
            return json(['code' => 505, 'msg' => 'openid呢？']);
        }
        if(!empty(input("param.car_ids"))){
            $car_ids=json_decode(input("param.car_ids"));
        }else{
            return json(['code' => 502, 'msg' => '数组呢']);
        }
        // $data['deduct_moneys']=input("param.deduct_moneys");
        $data['deduct_moneys']=0;
        if(!empty(input("param.pay_fees"))){
            $data['pay_fees']=input("param.pay_fees");
        }else{
            return json(['code' => 506, 'msg' => '支付金额']);
        }
        if(!empty(input("param.name"))){
            $data['name']=input("param.name");
        }else{
            return json(['code' => 508, 'msg' => '收货人']);
        }
        if(!empty(input("param.phone"))){
            $data['phone']=input("param.phone");
        }else{
            return json(['code' => 509, 'msg' => '收货电话']);
        }
        if(!empty(input("param.address"))){
            $data['address']=input("param.address");
        }else{
            return json(['code' => 510, 'msg' => '收货地址']);
        }
        if(!empty(input("param.address_id"))){
            $data['address_id']=input("param.address_id");
        }else{
            return json(['code' => 513, 'msg' => '默认收货地址id']);
        }
        if(!empty(input("param.message"))){
            $data['message']=input("param.message");
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $data['user_id']=$uid;
        if ($car_ids[0]->type==1) {
            $body=Db::name('product')->where('id',$car_ids[0]->p_id)->value('title');
        }elseif($car_ids[0]->type==2) {
            $body=Db::name('scenic_spot')->where('id',$car_ids[0]->p_id)->value('title');
        }
        $data['p_id']=$car_ids[0]->p_id;
        $data['pay_style']=2;
        $data['buy_num']=$car_ids[0]->buy_num;
        $data['price']=$car_ids[0]->money;
        $data['spec_combination_id']=$car_ids[0]->spec_combination_id;
        $data['combination']=$car_ids[0]->combination;
        $data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
        $data['state']=1;
        $data['is_cart']=2;
        $data['order_type']=3;
        if(count($car_ids)>1){
            $data['sub']=2;
        }elseif(count($car_ids)==1){
            $data['sub']=1;
        }
        $data['time']=time();
        $data['uptime']=time();

        $commission_scale=Db::name('system_set')->where('id',1)->value('commission_scale');//购买n元上级获佣金比例
        $commission=bcmul($data['pay_fees'],bcdiv($commission_scale,100,4),2);

        Db::startTrans();
        try {
            $orderId=Db::name('orders')->insertGetId($data);

            foreach ($car_ids as $key => $value) {
                $datasub['user_id']=$uid;
                $datasub['orders_id']=$orderId;
                if ($car_ids[$key]->type==1) {
                    $datasub['title']=Db::name('product')->where('id',$car_ids[$key]->p_id)->value('title');
                }elseif($car_ids[$key]->type==2) {
                    $datasub['title']=Db::name('scenic_spot')->where('id',$car_ids[$key]->p_id)->value('title');
                }
                $datasub['ordernosub']=$data['orderno'].$key;
                $datasub['cart_id']=$car_ids[$key]->id;
                $datasub['p_id']=$car_ids[$key]->p_id;
                $datasub['buy_num']=$car_ids[$key]->buy_num;
                $datasub['price']=$car_ids[$key]->money;
                $datasub['spec_combination_id']=$car_ids[$key]->spec_combination_id;
                $datasub['combination']=$car_ids[$key]->combination;
                $datasub['deduct_money']=0;
                $datasub['pay_fee']=bcmul($datasub['buy_num'],$datasub['price'],2);
                // $datasub['deduct_money']=bcdiv($data['deduct_moneys'],count($car_ids),2);
                // $datasub['pay_fee']=bcsub(bcmul($datasub['buy_num'],$datasub['price'],2),$datasub['deduct_money'],2);
                if($car_ids[$key]->type==1){
                    $datasub['order_type']=1;
                    Db::name('spec_combination')->where('id',$car_ids[$key]->spec_combination_id)->setDec('num',$car_ids[$key]->buy_num);//减库存
                }elseif($car_ids[$key]->type==2){
                    $datasub['order_type']=2;
                }
                $datasub['state']=1;
                $datasub['time']=time();
                $datasub['uptime']=time();
                Db::name('ordersub')->insert($datasub);
                Db::name('carts')->where('id',$car_ids[$key]->id)->update(['state'=>3,'uptime'=>time()]);
            }

            //购物车下单不支持佣金抵扣(分订单里不好分配,平方会出现有的支付金额为负;按比例分闲麻烦)

            // 提交事务
            Db::commit();
            $weixinpay = new WxpayTmd($this->appid,$openid,$this->mch_id,$this->apikey,$data['orderno'],$body.'...',floatval($data['pay_fees'] * 100),$this->request->domain());
            $return=$weixinpay->pay();
            return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '事物回滚失败！']);
        }
    }
    // 待付款
    public function wtopay()
    {
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.openid"))){
            $openid=input("param.openid");
        }else{
            return json(['code' => 505, 'msg' => 'openid呢？']);
        }
        if(!empty(input("param.id"))){
            $id=input("param.id");
        }else{
            return json(['code' => 502, 'msg' => 'id呢？']);
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $order=Db::name('ordersub')->where('user_id',$uid)->where('id',$id)->find();
        $weixinpay = new WxpayTmd($this->appid,$openid,$this->mch_id,$this->apikey,$order['ordernosub'],$order['title'],floatval($order['pay_fee'] * 100),$this->request->domain());
        $return=$weixinpay->pay();
        return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
    }
    // 取消支付
    public function cancel()
    {
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.id"))){
            $id=input("param.id");
        }else{
            return json(['code' => 502, 'msg' => 'id呢？']);
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $deduct_moneys= Db::name('ordersub')->field('orders_id,deduct_money')->where(array('user_id'=>$uid,'id'=>$id))->find();
        Db::startTrans();
        try {
            Db::name('ordersub')->where(array('user_id'=>$uid,'id'=>$id,'state'=>1))->update(['state'=>6]);
            if($deduct_moneys['deduct_money']>0){
                Db::name('users')->where('id', $uid)->setInc('money',$deduct_moneys['deduct_money']);
                // Db::name('money_bill')->where('type',2)->where('user_id', $uid)->where('orders_id', $deduct_moneys['orders_id'])->setDec('money',$deduct_moneys['deduct_moneys']);
                Db::name('money_bill')->where('type',2)->where('user_id', $uid)->where('orders_id', $deduct_moneys['orders_id'])->update(['money'=>0,'uptime'=>time()]);
            }
            // 提交事务
            Db::commit();
            return json(['code' => 200, 'msg' => '成功！']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '事物回滚失败！']);
        }
    }
    //已到货
    public function orderFinish()
    {
        if(!empty(input("param.token"))){
            $token=input("param.token");
        }else{
            return json(['code' => 501, 'msg' => '令牌呢？']);
        }
        if(!empty(input("param.id"))){
            $id=input("param.id");
        }else{
            return json(['code' => 502, 'msg' => '订单id呢']);
        }
        $uid=UserCrypt::do_mdecrypt($token);
        $res=Db::name('ordersub')->where('state',3)->where('user_id', $uid)->where('id',$id)->update(['state'=>4,'uptime'=>time()]);
        if ($res) {
            return json(['code' => 200, 'msg' => '成功！']);
        }else{
            return json(['code' => 500, 'msg' => '失败！']);
        }
    }
}